package com.example.preferencesexample;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;

public class MainActivity extends Activity {
	private Context mContext;
	private SharedPreferences mPrefs;
	private SharedPreferences.Editor mPrefEditor;
	
	private CheckBox mCheck1;
	private CheckBox mCheck2;
	private CheckBox mCheck3;
	private Button mLoadButton;
	private Button mSaveButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_main);
		
		//Get an instance of the preferences
		mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		mPrefEditor = mPrefs.edit();
		
		//Find checkboxes
		mCheck1 = (CheckBox) findViewById(R.id.check1);
		mCheck2 = (CheckBox) findViewById(R.id.check2);
		mCheck3 = (CheckBox) findViewById(R.id.check3);
		
		//Setup Buttons
		mLoadButton = (Button) findViewById(R.id.load);
		mLoadButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//When "Load" is clicked,
				loadSettings();
			}
		});
		
		mSaveButton = (Button) findViewById(R.id.save);
		mSaveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//When "Save" is clicked,
				saveSettings();
			}
		});
	}
	
	/**
	 * Set the checkboxes to 
	 * what they were last saved as.
	 * If nothing was ever saved,
	 * all of the checkboxes will not
	 * be checked.
	 */
	private void loadSettings(){
		mCheck1.setChecked(
			mPrefs.getBoolean("check1_checked", false));
		mCheck2.setChecked(
				mPrefs.getBoolean("check2_checked", false));
		mCheck2.setChecked(
				mPrefs.getBoolean("check2_checked", false));
	}

	/**
	 * Save the state  of the checkboxes
	 */
	private void saveSettings(){
		mPrefEditor.putBoolean("check1_checked", 
						mCheck1.isChecked());
		mPrefEditor.putBoolean("check2_checked", 
				mCheck2.isChecked());
		mPrefEditor.putBoolean("check3_checked", 
				mCheck3.isChecked());
		//apply the changes
		mPrefEditor.apply();
	}
	
	
	
}

